<template>
  <div class="schedule-add">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">新增排班</div>
      </template>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="96px">
        <el-form-item label="月份" prop="monthYm">
          <el-select v-model="form.monthYm" placeholder="选择月份" filterable style="width: 200px">
            <el-option v-for="m in monthOptions" :key="m" :label="m" :value="m" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间" prop="scheduleDate">
          <el-date-picker v-model="form.scheduleDate" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="紧急排班" prop="isUrgentSchedule">
          <el-switch v-model="form.isUrgentSchedule" />
        </el-form-item>
        <el-form-item label="紧急订单" prop="isUrgentOrder">
          <el-switch v-model="form.isUrgentOrder" />
        </el-form-item>

        <el-form-item label="选择班组" required>
          <el-table :data="teams" height="220" size="small" border @row-click="(row: any)=>form.teamId=row.teamId">
            <el-table-column label="选择" width="64">
              <template #default="{ row }">
                <el-radio v-model="form.teamId" :label="row.teamId" />
              </template>
            </el-table-column>
            <el-table-column prop="teamId" label="ID" width="100" />
            <el-table-column prop="teamName" label="班组名称" />
            <el-table-column prop="teamStatus" label="状态" width="100">
              <template #default="{ row }">
                <el-tag v-if="row.teamStatus==1" type="success" effect="plain">启用</el-tag>
                <el-tag v-else type="info" effect="plain">禁用</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="选择班次" required>
          <el-table :data="shifts" height="220" size="small" border @row-click="(row: any)=>pickShift(row)">
            <el-table-column label="选择" width="64">
              <template #default="{ row }">
                <el-radio v-model="form.shiftId" :label="row.shiftId" />
              </template>
            </el-table-column>
            <el-table-column prop="shiftId" label="ID" width="100" />
            <el-table-column prop="shiftName" label="班次名称" />
            <el-table-column prop="startTime" label="上班" width="120" />
            <el-table-column prop="endTime" label="下班" width="120" />
            <el-table-column prop="displayColor" label="颜色" width="120">
              <template #default="{ row }">
                <span class="color-dot" :style="{ backgroundColor: row.displayColor }"></span>{{ row.displayColor }}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="选择日历" prop="calenDarId">
          <el-alert type="info" :closable="false" show-icon title="已按月份选择，将自动匹配该日期对应的日历记录" />
        </el-form-item>
      </el-form>

      <div class="actions">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" :loading="saving" @click="save">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const read = getReadClient(1)
const write = getWriteClient(1)

const formRef = ref()
const form = ref<any>({
  teamId: undefined,
  shiftId: undefined,
  scheduleDate: '',
  isUrgentSchedule: false,
  isUrgentOrder: false,
  calenDarId: undefined,
  shiftName: '',
  monthYm: '',
})
const rules = {
  monthYm: [{ required:true, message:'请选择月份', trigger:'change' }],
  scheduleDate: [{ required:true, message:'请选择日期时间', trigger:'change' }],
  teamId: [{ required:true, message:'请选择班组', trigger:'change' }],
  shiftId: [{ required:true, message:'请选择班次', trigger:'change' }],
  // 由月份自动匹配 calenDarId
}
const saving = ref(false)
const teams = ref<any[]>([])
const shifts = ref<any[]>([])
const calendars = ref<any[]>([])
const monthOptions = ref<string[]>([])
const pickedShift = ref<any>(null)

function goBack(){ router.back() }
function pickShift(row:any){ pickedShift.value = row; form.value.shiftName = row?.shiftName || '' }

async function loadFK(){
  try{
    const [teamRes, shiftRes, calRes] = await Promise.all([
      read.get('schedread/api/Team/GetTeam', { params:{ pageindex:1, pagesize:1000 } }),
      read.get('schedread/api/Team/GetShift'),
      read.get('schedread/api/Calendar/GetList/list')
    ])
    const tdata = teamRes?.data?.data
    teams.value = tdata?.data || tdata || []
    const sdata = shiftRes?.data
    shifts.value = Array.isArray(sdata) ? sdata : (sdata?.data ?? sdata?.items ?? [])
    const cdata = calRes?.data
    calendars.value = Array.isArray(cdata) ? cdata : (cdata?.data ?? cdata?.items ?? [])

    // 生成月份下拉选项（YYYY-MM 去重）
    const set = new Set<string>()
    calendars.value.forEach((x:any)=>{
      const d = x?.calendarDate || x?.CalendarDate
      const ym = toYm(String(d||''))
      if(ym) set.add(ym)
    })
    // 确保至少包含当前月
    set.add(new Date().toISOString().slice(0,7))
    monthOptions.value = Array.from(set).sort()
    if(!form.value.monthYm) form.value.monthYm = new Date().toISOString().slice(0,7)
  }catch(e:any){
    ElMessage.error(e?.message || '外键数据加载失败')
  }
}

onMounted(()=>{
  // 优先使用路由中的月份
  const q = String(route.query.month || '').trim()
  if(/^\d{4}-\d{2}$/.test(q)){
    form.value.monthYm = q
  }else{
    const saved = localStorage.getItem('sched-current-month') || ''
    if(/^\d{4}-\d{2}$/.test(saved)) form.value.monthYm = saved
  }
  loadFK()
})

function toISO(dateStr:string){
  if(!dateStr) return ''
  if(/T\d{2}:\d{2}:\d{2}$/.test(dateStr)) return dateStr + 'Z'
  const d = new Date(dateStr)
  return isNaN(d.getTime()) ? dateStr : d.toISOString()
}

function toYm(dateLike:string){
  if(!dateLike) return ''
  const s = String(dateLike)
  if(/^\d{4}-\d{2}-\d{2}/.test(s)) return s.slice(0,7)
  if(/^\d{4}-\d{2}$/.test(s)) return s
  const d = new Date(s)
  if(!isNaN(d.getTime())) return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`
  return ''
}

function pickCalendarIdByDate(isoDate:string){
  const day = isoDate.slice(0,10)
  // 先精确匹配当天
  let found = calendars.value.find((x:any)=>{
    const cd = String(x?.calendarDate || x?.CalendarDate || '')
    return cd.startsWith(day)
  })
  if(found) return found.calendarId || found.calenDarId || found.id
  // 再按月份任取一个记录
  const ym = isoDate.slice(0,7)
  found = calendars.value.find((x:any)=>{
    const cd = String(x?.calendarDate || x?.CalendarDate || '')
    return cd.startsWith(ym)
  })
  if(found) return found.calendarId || found.calenDarId || found.id
  return undefined
}

async function save(){
  try{
    // @ts-ignore
    await formRef.value?.validate()
    saving.value = true
    const payload:any = {
      teamId: form.value.teamId,
      shiftId: form.value.shiftId,
      scheduleDate: toISO(form.value.scheduleDate),
      isUrgentSchedule: !!form.value.isUrgentSchedule,
      isUrgentOrder: !!form.value.isUrgentOrder,
      calenDarId: form.value.calenDarId,
    }
    // 按月份与日期自动匹配日历ID
    if(!payload.calenDarId && payload.scheduleDate){
      const autoId = pickCalendarIdByDate(String(payload.scheduleDate))
      if(autoId!=null) payload.calenDarId = autoId
    }
    if(pickedShift.value?.shiftName) payload.shiftName = pickedShift.value.shiftName

    await write.post('schedwrite/api/Team/AddSchedule', payload)
    try{
      const iso = payload.scheduleDate as string
      const ym = typeof iso === 'string' ? iso.slice(0,7) : ''
      const name = pickedShift.value?.shiftName || ''
      if(ym && name){ localStorage.setItem(`sched-default-${ym}`, name) }
      // 记录最近使用的月份
      if(form.value.monthYm){ localStorage.setItem('sched-current-month', form.value.monthYm) }
    }catch{}
    ElMessage.success('新增成功')
    // 成功后跳转到列表并携带月份
    const ym = form.value.monthYm || (typeof payload.scheduleDate==='string' ? payload.scheduleDate.slice(0,7) : '')
    router.push({ path:'/Main/ScheduliList', query: ym ? { month: ym } : undefined })
  }catch(e:any){
    ElMessage.error(e?.message || '新增失败')
  }finally{
    saving.value = false
  }
}
</script>

<style scoped>
.schedule-add{ padding: 16px; }
.card-header{ font-weight: 600; }
.actions{ margin-top: 12px; display:flex; gap:8px; }
.color-dot{ display:inline-block; width:14px; height:14px; border-radius:4px; border:1px solid #e5e7eb; margin-right:6px; vertical-align:middle; }
</style>


